package com.share.bio;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author caifan
 * @createTime 2020/5/2
 * @desc:
 */
public class SocketServer {

    public static void main(String[] args) throws Exception {
        final ServerSocket serverSocket = new ServerSocket(9400);

        while (true) {
            System.out.println("等待连接...");
            final Socket accept = serverSocket.accept();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        handler(accept);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

    }

    private static void handler(Socket socket) throws IOException  {
        System.out.println("thread name :" + Thread.currentThread().getName());
        byte[] buf = new byte[1024];
        System.out.println("准备读...");
        //接受客户端数据，没有数据阻塞
        int read = socket.getInputStream().read(buf);
        System.out.println("read完毕。。");
        if(read != -1) {
            System.out.println("接收到客户端的数据："+ new String(buf,0, read));
            System.out.println("thread id = "+ Thread.currentThread().getName());
        }
        socket.getOutputStream().write("HelloClient".getBytes());
        socket.getOutputStream().flush();
    }

}
